package repository;

import annotation.DependencyInjection;
import annotation.Singleton;
import database.GroupRelationDatabase;
import entity.GroupRelation;

import java.time.LocalDateTime;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;

@Singleton
public class GroupRelationRepository {
    private GroupRelationDatabase database;

    @DependencyInjection
    public GroupRelationRepository(GroupRelationDatabase database) {
        this.database = database;
    }

    public void startWrite() {
        database.startWrite();
    }

    public void endWrite() {
        database.endWrite();
    }

    public void startRead() {
        database.startRead();
    }

    public void endRead() {
        database.endRead();
    }

    public List<GroupRelation> getByUsername(String username) {
        return database.getList().stream().filter(groupRelation -> groupRelation.getUsername().equals(username)).map(GroupRelation::new).collect(Collectors.toList());
    }

    public GroupRelation get(UUID groupId, String username) {
        return database.getList().stream().filter(groupRelation -> groupRelation.getGroupId().equals(groupId) && groupRelation.getUsername().equals(username)).map(GroupRelation::new).findAny().orElse(null);
    }

    public boolean updateTimestamp(UUID groupId, String username, LocalDateTime timestamp) {
        Optional<GroupRelation> result = database.getList().stream().filter(groupRelation -> groupRelation.getGroupId().equals(groupId) && groupRelation.getUsername().equals(username)).findAny();
        if (!result.isPresent()) {
            return false;
        }
        result.get().setTimestamp(timestamp);
        return true;
    }

    public void add(GroupRelation groupRelation) {
        database.getList().add(groupRelation);
    }

    public boolean remove(UUID groupId, String username) {
        Iterator<GroupRelation> iterator = database.getList().iterator();
        while (iterator.hasNext()) {
            GroupRelation groupRelation = iterator.next();
            if (groupRelation.getGroupId().equals(groupId) && groupRelation.getUsername().equals(username)) {
                iterator.remove();
                return true;
            }
        }

        return false;
    }

    public List<GroupRelation> getByGroupId(UUID groupId) {
        return database.getList().stream().filter(groupRelation -> groupRelation.getGroupId().equals(groupId)).map(GroupRelation::new).collect(Collectors.toList());
    }
}
